package com.coco.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class MyDiscoveryClient {

    @Resource
    private DiscoveryClient discoveryClient;

    @Resource
    private RestTemplate restTemplate;

    private static final String SERVICE_ID = "socketOne";

    @Value("${server.port}")
    private Integer port;

    public void sendMsgToService(String msg) {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        Map<String,String> params = new HashMap<>();
        params.put("msg",msg);
        System.out.println("需要发送的消息是: " +msg);
        List<ServiceInstance> instances = discoveryClient.getInstances(SERVICE_ID);
        if(instances != null && !instances.isEmpty()) {
            for(ServiceInstance instance : instances) {
                String host = instance.getHost();
                int servicePort = instance.getPort();
                log.info("服务器地址：{}:{}",host,servicePort);
                String url = "http://socketOne:"+servicePort+"/index/send?msg={msg}";
                if(host != addr.getHostAddress()) {
                    restTemplate.getForObject(url,String.class,params);
                }
            }
        }
    }

}
